const charset = require('superagent-charset');
const superagent =  charset(require('superagent'));
require('superagent-proxy')(superagent);

const {
    readTask,
} = require('./ti_logic_read_task');

const {
    sleep,
    logger,
    httpPost,
} = require('./util');


process.on('unhandledRejection', error => {
    //...不处理promise错误...
});

const httpProxyGet = (url, proxy) => {
	return new Promise((resolve, reject) => {
		superagent.get(url).timeout(20000).proxy(proxy)
			.set('user-agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36')
			.end((err, res) => {
				if (err) {
					return reject(err);
				}
				resolve(res.text);
			});
	});
}

//获取代理。由于获取代理接口有限频，所以要一个一个拿。
const queryProxyQueue = [];
const getIp = serial => {
    queryProxyQueue.push(serial);
    return new Promise(async (resolve) => {
        while (1) {
            //轮到自己取代理
            if (queryProxyQueue[0] != serial) {
                await sleep(1500);
                continue;
            }

            let ip_info;
            try {
                ip_info = await httpPost('http://webapi.http.zhimacangku.com/getip?num=1&type=2&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=');
                logger(serial, 'getIp=',ip_info);
            } catch(e) {
                return resolve('');
            } finally {
                //查询完毕，退出队列
                queryProxyQueue.shift();
            }
            const ip_result = JSON.parse(ip_info);
            if (!ip_result['data'] || ip_result['data'].length < 1) {
                resolve('');
            }
            const result = ip_result['data'][0];
            resolve('http://'+result['ip']+':'+result['port']);
        }
    });
}

(async () => {
    const tasks = await readTask();
    if (!tasks) return;

    for (const task of tasks) {
        if (task.status != 1) continue;

        //开启并发任务
        (async (serial) => {
            let proxy;
            while (1) {
                if (!proxy) {
                    proxy = await getIp(serial);
                }
                const fullUrl = 'https://www.ti.com.cn/storeservices/cart/opninventory?opn=' + encodeURIComponent(serial);
                let ret;
                let retJson;
                let stock;
                try {
                    ret = await httpProxyGet(fullUrl, proxy);
                    retJson = JSON.parse(ret);
                    if (!retJson.hasOwnProperty('inventory')) {
                        logger('查询出错', ret);
                        throw new Error('no inventory');
                    }
                    stock = retJson.inventory;
                } catch(e) {
                    //查询失败，重新取代理
                    proxy = await getIp(serial);
                    continue;
                }

                if (stock < 250) {
                    sleep(3000);
                    continue;
                }

                logger(`检测到规格${serial}有${stock}库存`);
                //todo:继续后面
            }
        })(task.serial);
    }
})();

